package com.echat.config.security.authention;

import com.echat.config.security.enums.LoginType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author chentl
 * @version V1.0
 * @Project MyAuthenticationFailHandler
 * @Title MyAuthenticationFailHandler.java
 * @Description 失败的权限认证处理器
 * @Package com.echat.config.security.authention
 * @date 2019/6/8 23:28
 * @Copyright: 上海顺益信息科技有限公司 All rights reserved.
 */
@Component
@Slf4j
public class MyAuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {

    /**
     * json 转换工具类
     */
    private ObjectMapper objectMapper;
    @Value("auth.security.browser.loginType")
    private String loginType;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        logger.info("登录失败");

        //如果是json 格式
        if (LoginType.JSON.equals(loginType)) {
            //设置状态码
            response.setStatus(500);
            //将 登录失败 信息打包成json格式返回
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(e));
        } else {
            //如果不是json格式，返回view
            super.onAuthenticationFailure(request, response, e);
        }

    }
}

